<?php
namespace Controllers;
use Models\UserModel;

class UserController extends CommonController {

    public function login() {
        $this->loginJump();
        if (!empty($_POST)) {
            $username = isset($_POST['username']) ? trim($_POST['username']) : '';
            if (empty($username)) return $this->responseJson(400, '用户名必须填写');
            $password = isset($_POST['password']) ? $_POST['password'] : '';
            if (empty($password)) return $this->responseJson(400, '密码必须填写');
            $userModel = new UserModel();
            $user = $userModel->getUserByUsername($username);
            if (empty($user)) return $this->responseJson(400, '该用户名未注册，请先注册');
            if (md5($password) != $user['password']) return $this->responseJson(400, '密码输入错误');

            $this->saveUserToSession($user);
            return $this->responseJson(200, '登录成功');
        } else {
            return $this->response('user/login');
        }
    }

    private function saveUserToSession($user) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
    }

    public function register() {
        // 分支 如果是注册操作完成注册功能，如果是注册页面 加载注册模板
        $this->loginJump();
        if (!empty($_POST)) {
            // 注册功能
           $username = isset($_POST['username']) ? trim($_POST['username']) : '';
           if (empty($username)) return $this->responseJson(400, '用户名必须填写');
           $password = isset($_POST['password']) ? $_POST['password'] : '';
           if (empty($password)) return $this->responseJson(400, '密码必须填写');
           $re_password = isset($_POST['re_password']) ? $_POST['re_password'] : '';
           if ($password != $re_password) return $this->responseJson(400, '两次密码输入不一致');

           $userModel = new UserModel();
           $user = $userModel->getUserByUsername($username);
           if (!empty($user)) return $this->responseJson(400, '该用户名已被占用');
           if ($userModel->add($username, md5($password))) {
               return $this->responseJson(200, '注册成功');
           } else {
               return $this->responseJson(400, '注册失败');
           }

        } else {
            return $this->response('user/register');
        }
    }

    public function logout() {
        unset($_SESSION['username'], $_SESSION['user_id']);
        echo '<script>window.location.href="/index.php?c=user&a=login";</script>'; exit;
    }

}